package com.thientan.controller

import java.text.SimpleDateFormat

import org.hibernate.transform.AliasToBeanResultTransformer

import grails.converters.JSON

import com.thientan.model.HopDong
import com.thientan.model.NhanVien
import com.thientan.model.enums.LoaiNhanVien
import com.thientan.model.enums.TrangThaiHopDong
import com.thientan.service.GiaoPhieuThuService
import com.thientan.utils.Constants
import com.thientan.utils.Utility

class GiaoPhieuThuController extends AbstractBaseController{
	GiaoPhieuThuService giaoPhieuThuService
	
	@Override
	Class getDomainClass(){
		null // Because we don't save on this screen
	}
	
	@Override
	Object getDomainService(){
		giaoPhieuThuService
	}
	
	@Override
	public String getDomainName() {
		null
	}

	@Override
	public String getDisplayFieldName() {
		null
	}
	
    def loadListOfThuNgan() {
		Map result = ["success" : true]
		List nhanViens = NhanVien.findAllByLoaiNhanVien(LoaiNhanVien.THU_NGAN)
		result.putAt("thuNgan", extractPropertiesAsMaps(nhanViens, ["id", "maNv"]))
		render result as JSON
	}
	
	@Override
	protected Map buildExportData(Map exportParams){
		Long thuNganId = params['id'] as Long
		
		// Query data
		List listOfHopDong = HopDong.withCriteria {
			eq('nvThuNgan.id', thuNganId)
			eq('trangThai', TrangThaiHopDong.DANG_TRA_GOP)
			eq("daGiaoPhieu", true)
			projections {
				property('maHd', 'maHd')
				property('tienConLai', 'tienConLai')
			}
			resultTransformer(new AliasToBeanResultTransformer(HopDong.class))
		}
		
		// Prepare data for export
		return ['data' : extractPropertiesAsMapsWithOrderNumber(listOfHopDong, ['maHd', 'tienConLai'], true),
				'thuNgan' : NhanVien.findById(thuNganId).hoTen,
				'ngayBanGiao' : new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT).format(Calendar.getInstance().getTime()), 
				'tongSoHopDong' : listOfHopDong.size().toString(),
				'tongSoTienConLai' : Utility.moneyFormat(listOfHopDong.sum(0, {it.tienConLai ?: 0}))]
	}
	
	@Override
	protected String getExportFileName(){
		"PhieuBanGiaoPT"
	}
}